﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myomscl_web
{
    public abstract class BaseModuleRewriter : IHttpModule
    {
        public virtual void Init(HttpApplication app)
        {
            // WARNING!  This does not work with Windows authentication!
            // If you are using Windows authentication, 
            // change to app.BeginRequest
            app.AuthorizeRequest += new
               EventHandler(this.BaseModuleRewriter_AuthorizeRequest);
        }

        public virtual void Dispose() { }

        protected virtual void BaseModuleRewriter_AuthorizeRequest(
          object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            Rewrite(app.Request.Path, app);
        }

        protected abstract void Rewrite(string requestedPath,
          HttpApplication app);
    }

    public class ModuleRewriter : BaseModuleRewriter
    {
        protected override void Rewrite(string requestedPath,System.Web.HttpApplication app)
        {
            // get the configuration rules
            RewriterRuleCollection rules =
              RewriterConfiguration.GetConfig().Rules;

            // iterate through each rule...
            for (int i = 0; i < rules.Count; i++)
            {
                // get the pattern to look for, and 
                // Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" +
                  RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath,
                  rules[i].LookFor) + "$";

                // Create a regex (note that IgnoreCase is set...)
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                // See if a match is found
                if (re.IsMatch(requestedPath))
                {
                    // match found - do any replacement needed
                    string sendToUrl =
           RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath,
                       re.Replace(requestedPath, rules[i].SendTo));

                    // Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    break;      // exit the for loop
                }
            }
        }

    }
}